package com.siyu.rehearsal.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siyu.basedata.plan.domain.Plan;
import com.siyu.basedata.plan.mapper.PlanMapper;
import com.siyu.basedata.plan.service.IPlanService;
import com.siyu.common.config.minio.MinIOConfigProperties;
import com.siyu.common.constant.MinioOrOssConstants;
import com.siyu.common.core.domain.AjaxPageResult;
import com.siyu.common.utils.aliyun.service.FileOssStorageService;
import com.siyu.common.utils.minio.service.FileStorageService;
import com.siyu.rehearsal.dto.PlanPreviewDto;
import com.siyu.rehearsal.previewaffectv.domain.PreviewAffectV;
import com.siyu.rehearsal.previewaffectv.service.impl.PreviewAffectVServiceImpl;
import com.siyu.rehearsal.previewnd.domain.PreviewNd;
import com.siyu.rehearsal.previewnd.service.IPreviewNdService;
import com.siyu.rehearsal.previewpparameters.domain.PreviewPParameters;
import com.siyu.rehearsal.previewpparameters.service.impl.PreviewPParametersServiceImpl;
import com.siyu.rehearsal.previewpresult.domain.PreviewPResult;
import com.siyu.rehearsal.previewpresult.service.IPreviewPResultService;
import com.siyu.rehearsal.previewresult.domain.PreviewResult;
import com.siyu.rehearsal.previewresult.service.impl.PreviewResultServiceImpl;
import com.siyu.rehearsal.previewriska.domain.PreviewRiskA;
import com.siyu.rehearsal.previewriska.service.impl.PreviewRiskAServiceImpl;
import com.siyu.rehearsal.previewsresult.domain.PreviewSresult;
import com.siyu.rehearsal.previewsresult.service.IPreviewSresultService;
import com.siyu.rehearsal.service.PlanManageService;
import com.siyu.rehearsal.vo.PlanPreviewRespVo;
import com.siyu.rehearsal.vo.PlanVo;
import com.siyu.rehearsal.vo.PreviewPResultVo;
import com.siyu.rehearsal.vo.PreviewResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class PlanManageServiceImpl implements PlanManageService {

    private static Boolean minioOrOss = MinioOrOssConstants.getMinioOrOss();

    @Autowired
    private PreviewPParametersServiceImpl previewPParametersService;

    @Autowired
    private PreviewAffectVServiceImpl previewAffectVService;

    @Autowired
    private PreviewResultServiceImpl previewResultService;

    @Autowired
    private PreviewRiskAServiceImpl previewRiskAService;


    @Autowired
    private IPreviewPResultService previewPResultService;

    @Autowired
    private IPlanService planService;

    @Autowired
    private IPreviewSresultService previewSresultService;

    @Autowired
    private IPreviewNdService previewNdService;

    @Autowired
    private PlanMapper planMapper;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private MinIOConfigProperties minIOConfigProperties;

    @Autowired
    private FileOssStorageService fileOssStorageService;

    @Override
    public AjaxPageResult getPlanPreview(PlanPreviewDto planPreviewDto) {
        Page<Plan> page = new Page<>(planPreviewDto.getPageNum(), planPreviewDto.getPageSize());
        QueryWrapper<Plan> planQueryWrapper = new QueryWrapper<>();
        planQueryWrapper.select("create_by", "plan_name", "plan_type", "create_time", "plan_desc")
                .like(BeanUtil.isNotEmpty(planPreviewDto.getPlanName()),"plan_name",planPreviewDto.getPlanName())
                .eq("plan_type",planPreviewDto.getComputeType())
                .ge(BeanUtil.isNotEmpty(planPreviewDto.getCreateStartTime()),"create_time",planPreviewDto.getCreateStartTime())
                .le(BeanUtil.isNotEmpty(planPreviewDto.getCreateEndTime()),"create_time",planPreviewDto.getCreateEndTime())
                .eq("pre_type","预演");

        // 执行分页查询
        IPage<Plan> result = planMapper.selectPage(page, planQueryWrapper);

        // 获取分页数据
        List<Plan> records = result.getRecords(); // 分页后的数据列表
        long total = result.getTotal(); // 总记录数
        // 封装分页数据到自定义VO类或直接使用Map等，这里以自定义VO为例
        List<PlanPreviewRespVo> respList = new ArrayList<>();
        for (Plan plan : result.getRecords()) {
            PlanPreviewRespVo respVO = new PlanPreviewRespVo();
            // 将Plan实体转换为VO对象，根据实际需求映射字段
            respVO.setCreateBy(plan.getCreateBy());
            respVO.setPlanName(plan.getPlanName());
            respVO.setPlanType(plan.getPlanType());
            respVO.setCreateTime(plan.getCreateTime());
            respVO.setPlanDesc(plan.getPlanDesc());
            respList.add(respVO);
        }
        // 构建响应对象
        AjaxPageResult ajaxPageResult = new AjaxPageResult();
        ajaxPageResult.setRecords(respList); // 设置数据列表
        ajaxPageResult.setTotal(result.getTotal()); // 设置总记录数

        return ajaxPageResult;
    }

    @Override
    public PreviewPResultVo getOpenPlan(String id) {
        // 根据id查询预演计算的结果
        QueryWrapper<PreviewPResult> previewPResultQueryWrapper = new QueryWrapper<>();
        previewPResultQueryWrapper.eq("plan_id", id);
        PreviewPResult previewPResult = previewPResultService.getOne(previewPResultQueryWrapper);

        PreviewPResultVo previewPResultVo = new PreviewPResultVo();
        BeanUtil.copyProperties(previewPResult,previewPResultVo);

        // 根据id查询预演计算结果的指标数据
        QueryWrapper<PreviewResult> previewResultQueryWrapper = new QueryWrapper<>();
        previewResultQueryWrapper.eq("plan_id", id);
        List<PreviewResult> PreviewResults = previewResultService.list(previewResultQueryWrapper);
        ArrayList<PreviewResultVo> previewResultVos = new ArrayList<>();
        for (int i = 0; i < PreviewResults.size(); i++) {
            PreviewResult previewResult = PreviewResults.get(i);
            PreviewResultVo previewResultVo = new PreviewResultVo();
            // 复制PreviewResult到PreviewResultVo对象中输出
            BeanUtil.copyProperties(previewResult,previewResultVo);
            previewResultVos.add(previewResultVo);
        }

        previewPResultVo.setIndicatorData(previewResultVos);

        return previewPResultVo;
    }

    @Override
    @Transactional
    public void deletePlan(List<String> ids) {
        for (String id : ids) {
            //删除预演方案
            planService.deletePlanById(id);

            //删除预演方案参数
            //QueryWrapper<PreviewPParameters> previewPParametersQueryWrapper = new QueryWrapper<>();
            //previewPParametersQueryWrapper.eq("plan_id", id);
            //previewPParametersService.remove(previewPParametersQueryWrapper);

            //删除预演结果村庄影响
            QueryWrapper<PreviewAffectV> previewAffectVQueryWrapper = new QueryWrapper<>();
            previewAffectVQueryWrapper.eq("plan_id", id);
            previewAffectVService.remove(previewAffectVQueryWrapper);

            //删除预演方案计算结果
            QueryWrapper<PreviewPResult> previewPResultQueryWrapper = new QueryWrapper<>();
            previewPResultQueryWrapper.eq("plan_id", id);
            previewPResultService.remove(previewPResultQueryWrapper);

            //删除预演方案计算结果指标数据
            QueryWrapper<PreviewResult> previewResultQueryWrapper = new QueryWrapper<>();
            previewResultQueryWrapper.eq("plan_id", id);
            previewResultService.remove(previewResultQueryWrapper);

            //删除预演方案结果风险评估数据
            QueryWrapper<PreviewRiskA> previewRiskAQueryWrapper = new QueryWrapper<>();
            previewRiskAQueryWrapper.eq("plan_id", id);
            previewRiskAService.remove(previewRiskAQueryWrapper);

            //删除预演方案结果风险评估数据
            QueryWrapper<PreviewSresult> previewSresultQueryWrapper = new QueryWrapper<>();
            previewSresultQueryWrapper.select("geojson")
                    .eq("plan_id", id);
            PreviewSresult previewSresult = previewSresultService.getOne(previewSresultQueryWrapper);

            // 删除minio文件
            List<String> list = Convert.toList(String.class, previewSresult.getGeojson());
            if (list.size()!=0 && list!=null){
                for (String planUrl : list) {
                    if (minioOrOss){
                        try {
                            // oss 删除
                            fileOssStorageService.delete(planUrl);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }else {
                        try {
                            // minio删除文件
                            URL url = new URL(planUrl);
                            String path = url.getPath();
                            path = minIOConfigProperties.getEndpoint() + path;
                            fileStorageService.delete(path);
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            previewSresultService.remove(previewSresultQueryWrapper);

            // 删除预演需求的雨量数据

            QueryWrapper<PreviewNd> previewNdQueryWrapper = new QueryWrapper<>();
            previewNdQueryWrapper.eq("plan_id",id);
            previewNdService.remove(previewNdQueryWrapper);
        }
    }

    @Override
    public HashMap<String, ArrayList<PlanVo>> getPlan(PlanPreviewDto planPreviewDto) {
        QueryWrapper<Plan> planQueryWrapper = new QueryWrapper<>();
        planQueryWrapper.select("id","plan_name","plan_type")
                .like(BeanUtil.isNotEmpty(planPreviewDto.getPlanName()),"plan_name",planPreviewDto.getPlanName())
                .eq("pre_type","预演")
                .eq("rscd",planPreviewDto.getRscd())
                .orderByDesc("create_time");
        List<Plan> plans = planService.list(planQueryWrapper);
        ArrayList<PlanVo> qingjing = new ArrayList<>();
        ArrayList<PlanVo> lishi = new ArrayList<>();
        ArrayList<PlanVo> jiani = new ArrayList<>();
        ArrayList<PlanVo> quankui = new ArrayList<>();
        ArrayList<PlanVo> jiankui = new ArrayList<>();
        for (int i = 0; i < plans.size(); i++) {
            Plan plan = plans.get(i);
            PlanVo resultPlan = new PlanVo();
            resultPlan.setPlanName(plan.getPlanName());
            resultPlan.setId(plan.getId());
            if (plan.getPlanType().equals("情景")){
                qingjing.add(resultPlan);
            }
            if (plan.getPlanType().equals("历史")){
                lishi.add(resultPlan);
            }
            if (plan.getPlanType().equals("假拟")){
                jiani.add(resultPlan);
            }
            if (plan.getPlanType().equals("瞬间溃坝")){
                quankui.add(resultPlan);
            }
            if (plan.getPlanType().equals("逐渐溃坝")){
                jiankui.add(resultPlan);
            }
        }
        HashMap<String, ArrayList<PlanVo>> planResultMap = new HashMap<>();
        planResultMap.put("scene", qingjing);
        planResultMap.put("history", lishi);
        planResultMap.put("falsePlan", jiani);
        planResultMap.put("arout", quankui);
        planResultMap.put("grout", jiankui);

        return planResultMap;
    }
}
